<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/20/0020
 * Time: 14:21
 */

namespace App\Http\Controllers\Api\Admin;


use App\Http\Controllers\Api\Controller;
use App\Http\Requests\Api\GoodsRequest;
use App\Models\Good;
use App\Models\GoodCategory;
use App\Service\GoodService;
use App\Transformers\GoodslistTransformer;
use Dingo\Api\Http\Request;

class GoodsController extends Controller
{
    public function index(Request $request,Good $good){
        $query = $good->query();
        $params = $request->all();
        $where = [];
        if (!empty($params['goods_name'])){
            $query->where('goods_name','like','%' . $params['goods_name'] . '%');
        }

        if (!empty($params['is_hot'])){
            $query->where('is_hot','=','1');
        }

        //order 条件
        if (!empty($order=$params['order'])){
            $key = array_keys($order)[0];
            $value = array_values($order)[0];
            $query->orderBy("{$key}","{$value}");
        }

        $order = 'created_at';
        $goods = $query->orderBy($order,'desc')->paginate(20);

        return $this->response->paginator($goods,new GoodslistTransformer());
    }

    public function store(GoodsRequest $request,Good $good){
        $good->fill($request->all());
        $good->goods_sn = GoodService::goods_sn();
        //TODO  添加管理员
        //$good->admin_id =
        $good->save();

        return $this->response->array(['message'=>'添加成功'])->setStatusCode(201);
    }


    public function destory(Good $good){
        dd($this->user()->id);
        //TODO 权限
       $good->delete();

        return $this->response->noContent();
    }

    public function update(GoodsRequest $request,Good $good){
        //权限
        $good->update($request->all());

        return $this->response->array(['message'=>'更新成功'])->setStatusCode(200);
    }

    //根据商品名搜索
    public function goodsByName(Request $request,Good $good){
        $query = $good->query();
        if (!empty($request->get('goods_name'))){
            $query->where('goods_name','like','%' .$request->get('goods_name'). '%');
        }
        $res = $query->paginate(20);
        return $this->response->paginator($res,new GoodslistTransformer());
    }

    //添加到夺宝





}